#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
用户界面演示脚本
模拟用户交互来测试UI功能
"""

import os
import sys
import time
from pathlib import Path
from unittest.mock import patch

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

try:
    from core.utils import color_green, color_yellow, color_red, color_blue
    from apps.scenario_ui import ScenarioUI, print_banner, print_menu
    from modules.intelligence.scenario_template_engine import ScenarioType
except ImportError as e:
    print("导入模块失败: {}".format(e))
    sys.exit(1)

def simulate_user_input(inputs):
    """模拟用户输入"""
    input_iter = iter(inputs)
    
    def mock_input(prompt=""):
        try:
            value = next(input_iter)
            print(prompt + value)  # 显示模拟的输入
            return value
        except StopIteration:
            return "0"  # 默认退出
    
    return mock_input

def demo_ui_banner_and_menu():
    """演示UI横幅和菜单"""
    print(color_blue("🎨 演示UI横幅和菜单"))
    print("=" * 50)
    
    print_banner()
    print_menu()
    
    print(color_green("✓ UI横幅和菜单显示正常"))
    print()

def demo_ui_initialization():
    """演示UI初始化"""
    print(color_blue("🚀 演示UI初始化"))
    print("=" * 50)
    
    try:
        ui = ScenarioUI()
        print(color_yellow("设置信息:"))
        for key, value in ui.settings.items():
            print("  {}: {}".format(key, value))
        
        print(color_green("✓ UI初始化成功"))
        return ui
        
    except Exception as e:
        print(color_red("❌ UI初始化失败: {}".format(e)))
        return None

def demo_auto_scenario_detection(ui):
    """演示自动场景检测"""
    print(color_blue("🔍 演示自动场景检测"))
    print("=" * 50)
    
    try:
        # 模拟自动检测过程
        with patch('builtins.input', side_effect=['', '']):  # 模拟按回车键
            ui.init_system()
            
            # 调用场景检测
            detected_scenario, confidence = ui.system.detect_scenario()
            
            print(color_yellow("检测结果:"))
            print("  场景类型: {}".format(detected_scenario.value))
            print("  置信度: {:.2f}".format(confidence))
            
        print(color_green("✓ 自动场景检测演示完成"))
        
    except Exception as e:
        print(color_red("❌ 自动场景检测失败: {}".format(e)))

def demo_manual_scenario_selection(ui):
    """演示手动场景选择"""
    print(color_blue("🎯 演示手动场景选择"))
    print("=" * 50)
    
    try:
        # 模拟选择个人测试环境
        with patch('builtins.input', side_effect=['2', '2', '']):  # 选择个人测试，然后分析
            ui.init_system()
            
            # 模拟场景选择过程
            scenario_type = ScenarioType.PERSONAL_TESTING
            template = ui.system.select_scenario_template(scenario_type)
            
            if template:
                print(color_yellow("选择的场景模板:"))
                print("  名称: {}".format(template.name))
                print("  描述: {}".format(template.description))
                print("  置信度: {:.2f}".format(template.confidence_score))
                print("  功能数量: {}".format(len(template.features)))
            
        print(color_green("✓ 手动场景选择演示完成"))
        
    except Exception as e:
        print(color_red("❌ 手动场景选择失败: {}".format(e)))

def demo_one_click_deployment(ui):
    """演示一键部署"""
    print(color_blue("🚀 演示一键部署"))
    print("=" * 50)
    
    try:
        ui.init_system()
        
        # 模拟干运行部署
        result = ui.system.one_click_deploy(dry_run=True)
        
        print(color_yellow("部署结果:"))
        print("  成功: {}".format(result.get('success', False)))
        print("  干运行: {}".format(result.get('dry_run', False)))
        print("  消息: {}".format(result.get('message', '无消息')))
        
        if result.get('deployed_features'):
            print("  部署的功能:")
            for feature in result['deployed_features']:
                print("    - {}".format(feature))
        
        print(color_green("✓ 一键部署演示完成"))
        
    except Exception as e:
        print(color_red("❌ 一键部署失败: {}".format(e)))

def demo_scenario_analysis(ui):
    """演示场景分析"""
    print(color_blue("📊 演示场景分析"))
    print("=" * 50)
    
    try:
        ui.init_system()
        
        # 运行场景分析
        report = ui.system.run_scenario_analysis(
            scenario_type=ScenarioType.PERSONAL_TESTING,
            max_recommendations=3,
            risk_threshold=0.7,
            dry_run=True
        )
        
        print(color_yellow("分析报告:"))
        print("  场景类型: {}".format(report.get('scenario_type', '未知')))
        print("  检测置信度: {:.2f}".format(report.get('detection_confidence', 0)))
        
        if 'recommendations' in report:
            print("  推荐功能:")
            for rec in report['recommendations'][:3]:  # 显示前3个推荐
                print("    - {} (优先级: {})".format(
                    rec.get('feature', '未知'), 
                    rec.get('priority', '未知')
                ))
        
        if 'risk_assessment' in report:
            risk = report['risk_assessment']
            print("  风险评估:")
            print("    - 整体风险: {}".format(risk.get('overall_risk', '未知')))
            print("    - 检测概率: {:.2f}".format(risk.get('detection_probability', 0)))
        
        print(color_green("✓ 场景分析演示完成"))
        
    except Exception as e:
        print(color_red("❌ 场景分析失败: {}".format(e)))

def demo_settings_management(ui):
    """演示设置管理"""
    print(color_blue("⚙️ 演示设置管理"))
    print("=" * 50)
    
    try:
        # 显示当前设置
        print(color_yellow("当前设置:"))
        for key, value in ui.settings.items():
            print("  {}: {}".format(key, value))
        
        # 模拟修改设置
        original_level = ui.settings['optimization_level']
        ui.settings['optimization_level'] = 'aggressive'
        ui.save_settings()
        
        print(color_yellow("\n设置已修改为: aggressive"))
        
        # 恢复原始设置
        ui.settings['optimization_level'] = original_level
        ui.save_settings()
        
        print(color_yellow("设置已恢复为: {}".format(original_level)))
        
        print(color_green("✓ 设置管理演示完成"))
        
    except Exception as e:
        print(color_red("❌ 设置管理失败: {}".format(e)))

def run_ui_demo():
    """运行UI演示"""
    print(color_blue("🎭 场景化自动决策系统UI演示"))
    print("=" * 60)
    print()
    
    # 1. 演示UI横幅和菜单
    demo_ui_banner_and_menu()
    time.sleep(1)
    
    # 2. 演示UI初始化
    ui = demo_ui_initialization()
    if not ui:
        print(color_red("❌ UI初始化失败，停止演示"))
        return False
    
    time.sleep(1)
    
    # 3. 演示自动场景检测
    demo_auto_scenario_detection(ui)
    time.sleep(1)
    
    # 4. 演示手动场景选择
    demo_manual_scenario_selection(ui)
    time.sleep(1)
    
    # 5. 演示一键部署
    demo_one_click_deployment(ui)
    time.sleep(1)
    
    # 6. 演示场景分析
    demo_scenario_analysis(ui)
    time.sleep(1)
    
    # 7. 演示设置管理
    demo_settings_management(ui)
    
    print()
    print("=" * 60)
    print(color_green("🎉 UI演示完成！所有功能正常工作"))
    
    return True

if __name__ == "__main__":
    success = run_ui_demo()
    sys.exit(0 if success else 1)